﻿using DotNetty.Extensions;
using System.Net;
using System.Text;

var server = new WebSocketServer(8000);

//server.Path = "/kkk";

server.OnChannelPipeline += pipeline =>
{
    //心跳
    //pipeline.AddLast(new IdleStateHandler(60, 0, 0));

    //tls证书
    //var cert = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password");
    //pipeline.AddLast(TlsHandler.Server(cert));
};

server.OnStarting += () =>
{
    Console.WriteLine("Starting...");
};

server.OnStarted += () =>
{
    Console.WriteLine("Started.");
};

server.OnStopped += async ex =>
{
    Console.WriteLine($"Stopped==>{ex?.Message}");
    await Task.Delay(2000);
    await server.StartAsync(); //restart
};

server.OnClientConnected += cnn =>
{
    var addr = (IPEndPoint)cnn.Channel.RemoteAddress;

    Console.WriteLine($"ClientConnected==>{cnn.Id}==>IP:{addr.Address}==>Port:{addr.Port}");
    Console.WriteLine($"ClientCount：{server.ClientDict.Count}");
};

server.OnClientTextMessage += async (cnn, message) =>
{
    Console.WriteLine($"ClientTextMessage==>{cnn.Id}===>{message}");

    await cnn.WriteAndFlushAsync("this is from websocket server text message!");
};

server.OnClientBinaryMessage += async (cnn, bytes) =>
{
    var txt = Encoding.UTF8.GetString(bytes);
    Console.WriteLine($"ClientBinaryMessage==>{cnn.Id}===>{txt}");

    var bs = Encoding.UTF8.GetBytes("this is from websocket server binary message!");
    await cnn.WriteAndFlushAsync(bs);
};

server.OnClientException += (cnn, ex) =>
{
    Console.WriteLine($"ClientException==>{cnn.Id}==>{ex?.Message}");
};

server.OnClientDisconnected += cnn =>
{
    Console.WriteLine($"ClientDisconnected==>{cnn.Id}");
    Console.WriteLine($"ClientCount：{server.ClientDict.Count}");
};

await server.StartAsync();

Console.ReadKey();

await server.DisposeAsync();

Console.WriteLine("Hello, World!");
